<template>
	<van-collapse v-model="activeNames">
		<van-collapse-item :title="label" :required="required" name="1">
			<div class="upload">
				<van-uploader :after-read="afterRead" 
				@delete="deletFile" 
				:preview-full-image="true"
				@oversize="onOversize" 
				:max-size="1024 * 10 * 1024" :max-count="10" 
				:accept="accept"
				 v-model="fileList">

				</van-uploader>
			</div>
		</van-collapse-item>
	</van-collapse>
</template>

<script>
	import {uploadFile,getForm,openFile} from '@request/api.js'
	export default {
		data() {
			return {
				fileList: [],
				urlFileList:[],
				accept:'',
				activeNames: ['0'],
			};
		},
		props:['fieldName','required','label','fieldDefaultValue'],
		created(){
			getForm({
				'_url':'attach'
			}).then(res=>{
				if(res.code === 0){
					this.accept = res.data[0].attach
				}
			})
			// 图片文件回显
			if(this.fieldDefaultValue&&this.fieldDefaultValue !== ''){
				let arr = this.fieldDefaultValue.split(":")
				let fileItemList = []
				arr.forEach(item => {
					let arr2 = item.split("|")
					fileItemList.push({
						fileName: arr2[1],
						url: arr2[0]
					})
				})
				fileItemList.forEach(item => {
					this.urlFileList.push({
						original:item.fileName,
						url:item.url
					})
					this.base64(item)
				})
			}
		},
		methods: {
			async base64(item) {
				await openFile({
					'_form': this.$route.query.form_id,
					'_num': this.$route.query.num,
					'_fieldName': this.fieldName,
					'_filePath': item.url
				}).then(res => {
					this.fileList.push({
						content: `data:${res.contentType};base64,${res.base64}`,										file:{
							name: item.fileName,
							type: res.contentType,
							size: res.size,
						}
					})
				})
			},
			afterRead(file) {
				const form = new FormData();
				form.append("file", file.file);
				file.status = "uploading";
				file.message = "上传中...";
				this.$axios.post('/api/uploadFile?',form,{timeout:15000}).then(res=>{
					if (res.data.code == 0) {
					  this.$toast('上传成功');
					  file.status = "";
					  file.message = '上传完成'		
					  this.urlFileList.push({
						  original:res.data.info.original,
						  url:res.data.info.url
					  })
					}else{
						file.status = "failed";
						file.message = '上传失败'
					}
				}).catch(err=>{
						file.status = "failed";
						file.message = '上传失败'
				})				
			},
			onOversize(file) {
				this.$toast('上传文件过大！');
			},
			deletFile(file) {
				let arr = this.urlFileList.filter(item=>{
					if(item.original !== file.file.name){
						return true
					}
				})
				this.urlFileList = arr
			}
		}
	};
</script>

<style lang="scss" scoped>
	.van-collapse-item{
		/deep/ .van-collapse-item__content{
			background-color: $bg-1;
		}
		/deep/ .van-cell__title{
			color: #646566;
		}
	}
	.van-uploader{
		/deep/ .van-uploader__upload{
			width: vw(76);
			height: vw(76);
		}
		/deep/ .van-uploader__preview-image{
			width: vw(76);
			height: vw(76);
		}
	}
</style>
